package com.alks.function.service.impl.system;

import com.alibaba.excel.util.StringUtils;
import com.alks.common.aop.AutoPageAop;
import com.alks.entity.data.entity.SdProgram;
import com.alks.entity.data.page.PageParam;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.InDataException;
import com.alks.function.mapper.system.SYS_SdProgramMapper;
import com.alks.function.service.system.IProgramService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author MS
 * @since 2024/7/2下午2:11
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ProgramServiceImpl extends ServiceImpl<SYS_SdProgramMapper,SdProgram> implements IProgramService {
    private final SYS_SdProgramMapper programMapper;

    @Override
    @AutoPageAop
    public ResponseInfo programQuery(PageParam request, String prgId) {
        /*查询数据*/
        List<SdProgram> dtos = lambdaQuery()
                .eq(StringUtils.isNotBlank(prgId), SdProgram::getPrgId, prgId)
                .list();
        return ResponseInfo.ok(dtos);
    }

    @Override
    public ResponseInfo programAdd(SdProgram request) {
        prgIdDuplCheck(request);
        /*写入程序*/
        programMapper.insert(request);
        return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo programUpdate(SdProgram request, String oldPrgId) {
        /*判断是否重复*/
        prgIdDuplCheck(request);
        /*执行更新*/
        LambdaQueryWrapper<SdProgram> wrapper=new LambdaQueryWrapper<SdProgram>()
                .eq(SdProgram::getPrgId,oldPrgId);
        programMapper.update(request, wrapper);
        return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo programDelete(String oldPrgId) {
        /*删除字段*/
        programMapper.deleteById(oldPrgId);
        return ResponseInfo.ok();
    }


    /**
     * 程序ID查重
     * @param request
     */
    private @Nullable void prgIdDuplCheck(SdProgram request) {
        /*判断是否重复*/
        Integer count = lambdaQuery()
                .eq(SdProgram::getPrgId, request.getPrgId()).count();
        if (count!=0){
            throw new InDataException("程序代码已存在");
        }
    }
}
